/**
 *   By Luocheng Tang 
 *   
 *   This class is for single DB connection. Set as default load
 */
package com.lvmama.vst.batis.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.lvmama.vst.batis.dsobject.DataSourceUtil;
import com.lvmama.vst.batis.dsobject.DsObject;

@Profile({"develop"})
@Configuration
@ComponentScan("com.lvmama.vst.batis") 
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
public class SimpleDataSourceConfig {

	// user defined data source
	@Value("${spring.datasource.type: }")
	private String dataSourceType;

	// load data source from application.properties or application.yml
	@Autowired 
	@Qualifier("DsObjectSimple") 
	DsObject dsObject;  

	@ConditionalOnMissingBean({ DataSource.class})
	@Bean(name = "dataSource")
	public DataSource dataSource() throws Exception {
		// be careful the order
		String[] sourceArray = {this.dataSourceType, 
								DataSourceUtil.DRUID_DATA_SOURCE, 
								DataSourceUtil.TOMCAT_DATA_SOURCE };
		Class<? extends DataSource> targetClass = null;
		for (String sourceType : sourceArray) {
			targetClass = DataSourceUtil.classInClasspath(sourceType);
			if (null != targetClass) {
				break;
			}
		}
		return DataSourceUtil.objToDataSource(targetClass, this.dsObject);
	}
	
	// register data source to transaction
	@Bean
    public PlatformTransactionManager annotationDrivenTransactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
